<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-16 11:10:18
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-16
-->
<template>
  <RjModal
    width="800px"
    :title="$t('userManage.printModalTitle')"
    :visible="isVisible"
    @ok="onOk"
    @cancel="onCancel"
    :afterClose="afterClose"
  >
    <div class="mb-10">
      <b>{{ $t('common.tip') }}: {{ $t('userManage.printModalTip') }}</b>
      <a-tooltip :title="$t('userManage.printModalTip2')">
        <icon-font
          class="info-icon ml-5"
          :style="{
            fontSize: '15px',
          }"
          type="ic-info"
        />
      </a-tooltip>
    </div>
    {{ $t('userManage.printParamSetting') }}
    <a-form-model
      :labelCol="{ span: 6 }"
      labelAlign="left"
      :wrapperCol="{ span: 18 }"
      :model="form"
      :rules="rules"
      :colon="false"
    >
      <a-form-model-item :label="$t('userManage.printMethod')">
        <a-select v-model="printMethod" :options="printMethodOptions">
        </a-select>
      </a-form-model-item>

      <a-form-model-item :label="$t('userManage.printText')">
        <a-input :maxLength="40" v-model="text" allowClear />
      </a-form-model-item>

      <a-form-model-item :label="$t('userManage.printLogo')">
        <a-input :value="selectedLogo.fileName" readOnly>
          <template v-slot:suffix>
            <a-icon type="plus-circle" v-if="!expand" @click="expand = true" />
            <a-icon type="minus-circle" v-else @click="expand = false" />
          </template>
        </a-input>
        <div
          :class="['logo-wrapper', expand ? 'flex flex-wrap' : '']"
          v-show="expand"
        >
          <div
            :class="['logo', item.selected ? 'logo-selected' : '']"
            @click="select(index)"
            v-for="(item, index) in logoList"
            :key="item.id"
          >
            <img :src="item.url" height="40" width="116" alt="" />
            <div class="text-line-2 text-center">{{ item.fileName }}</div>
            <img
              v-show="item.selected"
              width="24"
              class="selected-icon"
              :src="selectedIcon"
              alt=""
            />
          </div>

          <div class="logo flex row-center" @click="uploadLogo">
            <div class="flex">
              <a-icon style="color: #bfbfbf" type="plus" /><span
                style="color: #bfbfbf"
                class="ml-5"
              >
                {{ $t('userManage.printAddLogo') }}</span
              >
            </div>
          </div>
          <img
            :src="deleteIcon"
            @click="del"
            class="del-btn"
            width="14"
            alt=""
          />
        </div>
      </a-form-model-item>

      <b class="font-15">{{ $t('userManage.printVoucherInfo') }}</b>
      <div class="font-10" style="#7D7D7D">
        {{ $t('userManage.printTip') }}
      </div>

      <a-form-model-item :wrapperCol="{ span: 24 }">
        <a-checkbox-group class="mt-20" v-model="params" name="checkboxgroup">
          <a-checkbox
            :key="index"
            :value="item.value"
            v-for="(item, index) in checkboxOptions"
            :disabled="!params.includes(item.value) && params.length >= 4"
          >
            {{ item.label }}
          </a-checkbox>
        </a-checkbox-group>
      </a-form-model-item>
      <div class="flex">
        <b>{{ $t('userManage.printPreview') }}</b>
        <img
          src="@/assets/images/configuration/preview.png"
          class="ml-5"
          width="16"
          alt=""
        />
      </div>

      <div class="w-320 mt-15 preview-wrapper" v-show="true" ref="preview">
        <img
          v-if="selectedLogo.url"
          :src="selectedLogo.url"
          height="40"
          alt=""
        />
        <div>
          <div>{{ $t('userManage.printVoucherCode') }}</div>
          <div class="text-center voucher-code">XXXXXX</div>
        </div>
        <div class="options flex flex-wrap">
          <div
            class="w-175"
            v-for="(item, index) in checkedOptions"
            :key="index"
          >
            <div>{{ item.label }}</div>
            <div>
              <b>{{ item.text }}</b>
            </div>
          </div>
        </div>
        <hr />
        <div class="text-center">
          {{ text }}
        </div>
      </div>
    </a-form-model>
    <UploadLogoModal @ok="queryLogos" v-model="uploadLogoModalShow" />
  </RjModal>
</template>

<script>
import deleteIcon from '@/assets/images/configuration/delete.png';
import { mapState } from 'vuex';
import { requestHttp, maccApi } from '@utils/index';
import selectedIcon from '@/assets/images/configuration/selected.png';
import UploadLogoModal from './UploadLogoModal.vue';
import i18n from '@/locales';
const options = {
  [i18n.t('portalAuth.policyName')]: 'XXXX',
  [i18n.t('userManage.printDownloadSpeed')]: '512Kbps',
  [i18n.t('userManage.printConcurrentDevices')]: '3',
  [i18n.t('userManage.printPeriod')]: i18n.tc('userManage.minutes', 30),
  [i18n.t('userManage.printDataQuota')]: '100MB',
  [i18n.t('userManage.printUploadSpeed')]: '512Kbps',
};
export default {
  components: {
    UploadLogoModal,
  },
  props: {
    list: Array,
  },
  data() {
    const checkboxOptions = [];
    for (let key in options) {
      checkboxOptions.push({
        label: key,
        value: key,
      });
    }
    return {
      isVisible: false,
      printView: false,
      screenWidth: 0,
      screenHeight: 0,
      form: {},
      rules: {},
      checkboxOptions,
      params: [
        this.$t('userManage.printProfileName'),
        this.$t('userManage.printDownloadSpeed'),
        this.$t('userManage.printConcurrentDevices'),
        this.$t('userManage.printPeriod'),
      ],
      printMethod: 'printTwoColumn',
      text: '',
      printMethodOptions: [
        {
          label: this.$t('userManage.print1Column'),
          value: 'printOneColumn',
        },
        {
          label: this.$t('userManage.print2Columns'),
          value: 'printTwoColumn',
        },
        {
          label: this.$t('userManage.printPOSReceipt'),
          value: 'printPosSlip',
        },
      ],
      expand: true,
      deleteIcon,
      logoList: [],
      selectedIcon,
      uploadLogoModalShow: false,
    };
  },
  created() {
    this.queryLogos();
    this.screenWidth = window.innerWidth;
    this.screenHeight = window.innerHeight;
  },
  watch: {
    module() {
      this.screenWidth = window.innerWidth;
      this.screenHeight = window.innerHeight;
    },
  },
  computed: {
    checkedOptions() {
      let checkedOptions = [];
      for (let key in options) {
        let label = this.params.find((item) => item == key);
        if (label) {
          checkedOptions.push({ label, text: options[key] });
        }
      }
      return checkedOptions;
    },
    ...mapState('User', ['tenantInfo']),
    ...mapState('Group', ['groupId']),
    ...mapState('I18n', ['lang']),
    selectedLogo() {
      return this.logoList.find((item) => item.selected) || {};
    },
  },
  mounted() {
    this.screenWidth = window.innerWidth;
    this.screenHeight = window.innerHeight;
  },
  methods: {
    openModal() {
      this.isVisible = true;
    },
    handlePirnt() {
      window.print();
    },
    onOk() {
      // this.$router.push('config_voucher_print_menu');

      let arr = [
        {
          key: 'packageName',
          style: 'showPackageName',
          value: 'packageName',
          label: i18n.t('userManage.printProfileName'),
        },
        {
          key: 'maxDownRateWithUnit',
          style: 'showDownload',
          value: 'downloadRateLimitObj',
          label: i18n.t('userManage.printDownloadSpeed'),
        },
        {
          key: 'maxClientsWithUnit',
          style: 'showConcurrent',
          value: 'noOfDeviceObj',
          label: i18n.t('userManage.printConcurrentDevices'),
        },
        {
          key: 'period',
          style: 'showPeriod',
          value: 'timePeriodObj',
          label: i18n.t('userManage.printPeriod'),
        },
        {
          key: 'quotaWithUnit',
          style: 'showData',
          value: 'quotaObj',
          label: i18n.t('userManage.printDataQuota'),
        },
        {
          key: 'bindMacStatusDesc',
          style: 'showBindMac',
          value: 'bindMac',
          label: i18n.t('userManage.printBindMac'),
        },
        {
          key: 'maxUpRateWithUnit',
          style: 'showUpload',
          value: 'uploadRateLimitObj',
          label: i18n.t('userManage.printUploadSpeed'),
        },
      ];
      let newList = [...this.list];
      let vouchers = [];
      newList.forEach((item) => {
        item.imgUrl = this.selectedLogo.url;
        item.customedText = this.text;
        arr.forEach((obj) => {
          item[obj.style] = false;
          item[obj.value] = item[obj.key];
        });
      });
      this.checkedOptions.forEach((option) => {
        newList.forEach((item) => {
          let style = arr.find((item2) => item2.label == option.label).style;
          item[style] = true;
        });
      });
      let zhugeEventMap = {
        printOneColumn: '打印（A4）单列',
        printTwoColumn: '打印（A4）两列',
        printPosSlip: '打印（POS）纸带',
      };
      this.zhugePoint(zhugeEventMap[this.printMethod], {
        workId: 'maccNetConf',
        funcId: 'macc-userMng',
      });
      vouchers = [...newList];
      window.vouchers = vouchers;
      let printMethod = this.printMethod;

      window.printMethod = printMethod;
      let host = location.host;
      let url;
      let protocol = location.protocol;
      let prefix;
      let lang = this.lang;
      let path;
      if (process.env.VUE_APP_MACC_CLOUD_ENV == 'private') {
        path = `pivatetest.rj.link/private-cloud/pages/configuration/authentication/voucher/printvoucher/`;
        prefix = 'https://';
      } else {
        path = `/admin3/${lang}/pages/configuration/authentication/voucher/printvoucher/`;
        prefix = protocol + '//' + host;
      }
      if (this.printMethod == 'printTwoColumn') {
        url = prefix + `${path}printvoucher2col.html`;
      } else if (this.printMethod == 'printOneColumn') {
        url = prefix + `${path}printvoucher1col.html`;
      } else {
        url = prefix + `${path}printvoucherpos.html`;
      }

      const locationPath = window.location.pathname;
      window.open(`${locationPath}#/voucherPrint`, '_blank');
      this.$emit('set', false);
    },
    select(index) {
      let selectedLogoIndex = this.logoList.findIndex((item) => item.selected);
      if (selectedLogoIndex !== null && selectedLogoIndex == index) {
        this.logoList[index].selected = false;
        return;
      }
      this.logoList.forEach((item) => {
        item.selected = false;
      });
      this.logoList[index].selected = true;
      this.form.logoName = this.logoList[index].fileName;
    },
    async queryLogos() {
      let querys = {
        groupIds: this.groupId,
        fileType: '',
        module: 'VOUCHER',
        pageSize: 8,
        pageIndex: 1,
      };
      let replaces = {
        tenantId: this.tenantInfo.tenantId,
      };
      let res = await requestHttp({
        api: `${maccApi.USER_MANAGE_VOUCHER_PRINT_GET_LOGO}`,
        method: 'GET',
        querys,
        replaces,
      });
      if (!res.code) {
        let protocol = location.protocol;
        let host = location.host;
        let domain;
        if (process.env.NODE_ENV !== 'production') {
          if (process.env.VUE_APP_MACC_CLOUD_ENV == 'private') {
            domain = 'http://172.29.45.136';
          } else {
            domain = 'https://cloudtest-as.ruijienetworks.com';
          }
        } else {
          domain = `${protocol}//${host}`;
        }
        const result = res.data || [];
        let list = result.map((item) =>
          Object.assign(item, {
            url: `${domain}${item.name}`,
            selected: false,
          })
        );
        // 非专享云
        if (!top.window.odmCUCfg) {
          let defaultLogo = {
            id: 0,
            fileName: 'default',
            url: `${domain}/intlfile/default/default_logo.png`,
            selected: true,
          };
          this.logoList = [defaultLogo, ...list];
          // 专享云
        } else {
          list.length && (list[0].selected = true);
          this.logoList = list;
        }
        this.form.logoName = this.logoList[0].fileName;
      }
    },
    onCancel() {
      this.screenWidth = window.innerWidth;
      this.screenHeight = window.innerHeight;
      this.isVisible = false;
    },
    del() {
      if (!Reflect.ownKeys(this.selectedLogo).length) {
        return this.$message.warning(this.$t('userManage.selectLogo'));
      }
      this.$confirm({
        title: this.$t('userManage.message'),
        content: this.$t('userManage.printDeleteLogo'),
        onOk: async () => {
          let querys = {
            ids: this.selectedLogo.id,
          };
          let res = await requestHttp({
            api: `${maccApi.USER_MANAGE_VOUCHER_PRINT_DEL_LOGO}`,
            method: 'DELETE',
            querys,
          });
          if (!res.code) {
            this.$message.success(this.$t('userManage.success'));
            this.queryLogos();
          } else {
            this.$message.warning(res.msg);
          }
        },
      });
    },
    uploadLogo() {
      this.uploadLogoModalShow = true;
    },
    afterClose() {
      this.text = '';
      this.printMethod = 'printTwoColumn';
      this.expand = true;
      this.params = [
        this.$t('userManage.printProfileName'),
        this.$t('userManage.printDownloadSpeed'),
        this.$t('userManage.printConcurrentDevices'),
        this.$t('userManage.printPeriod'),
      ];
      this.logoList.forEach((item) => {
        item.selected = false;
      });
    },
  },
};
</script>

<style lang="less" scoped>
::v-deep .ant-checkbox-wrapper {
  margin-left: 0;
  width: 240px;
}
.flex {
  display: flex !important;
  flex-direction: row !important;
  align-items: center;
}

.flex-wrap {
  flex-wrap: wrap !important;
}

.row-center {
  justify-content: center !important;
}

.preview-wrapper {
  border: 1px solid #ccc;
  color: #000;
  padding: 8px;
  font-size: 12px;
  img {
    display: block;
    margin: 0 auto;
    max-width: 160px;
    height: 40px;
  }
  .voucher-code {
    font-size: 20px;
  }
}
.logo-wrapper {
  padding: 12px 16px;
  background: #e8e8e8;
  position: relative;
  border-radius: 4px;
  .logo {
    width: 150px;
    padding: 5px 17px;
    background: #fff;
    height: 95px;
    line-height: 20px;
    margin: 24px 25px 24px 0;
    position: relative;
    border-radius: 4px;
    cursor: pointer;
    .selected-icon {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
  .logo-selected {
    border: 1px solid #2b6afd;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.25);
  }
  .del-btn {
    position: absolute;
    right: 16px;
    bottom: 12px;
    cursor: pointer;
  }
}
.mb-10 {
  margin-bottom: 10px;
}
.ml-5 {
  margin-left: 5px;
}
.text-line-2 {
  overflow: hidden;
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box; // 弹性伸缩盒
  -webkit-box-orient: vertical; // 设置伸缩盒子元素排列方式
  -webkit-line-clamp: 2;
}
.text-center {
  text-align: center;
}
.font-15 {
  font-size: 15px;
}
.font-10 {
  font-size: 10px;
}
.mt-20 {
  margin-top: 20px;
}
.w-320 {
  width: 340px;
}
.mt-15 {
  margin-top: 15px;
}
.w-175 {
  width: 160px;
}
.printPage {
  width: 100%;
}
@media print {
  body,
  .ant-modal-mask,
  .ant-modal-wrap {
    overflow: hidden !important;
  }
}
</style>
